package email.becode.simultaneous_interpretation_android.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import email.becode.simultaneous_interpretation_android.audio.AudioRecorder
import email.becode.simultaneous_interpretation_android.audio.AudioRecordService
import email.becode.simultaneous_interpretation_android.audio.AudioSource
import email.becode.simultaneous_interpretation_android.data.AppDatabase
import email.becode.simultaneous_interpretation_android.data.PreferencesManager
import email.becode.simultaneous_interpretation_android.data.TranslationRecord
import email.becode.simultaneous_interpretation_android.translation.TranslationService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.*

class TranslationViewModel(application: Application) : AndroidViewModel(application) {
    private val audioRecordService = AudioRecordService()
    private val translationService = TranslationService()
    private val audioRecorder = AudioRecorder(application)
    private val translationDao = AppDatabase.getDatabase(application).translationDao()
    private val preferencesManager = PreferencesManager(application)
    
    private var currentAudioPath: String? = null

    private val _uiState = MutableStateFlow(TranslationUiState())
    val uiState: StateFlow<TranslationUiState> = _uiState.asStateFlow()

    val savedRecords = translationDao.getAllRecords()
    val savedApiKey = preferencesManager.apiKey

    data class TranslationUiState(
        val isRecording: Boolean = false,
        val sourceLanguage: String = TranslationService.LANGUAGE_CHINESE,
        val sourceTexts: List<String> = emptyList(),
        val translations: List<Map<String, String>> = emptyList(),
        val selectedAudioSource: AudioSource = AudioSource.MICROPHONE,
        val error: String? = null
    )

    fun saveApiKey(apiKey: String) {
        viewModelScope.launch {
            preferencesManager.saveApiKey(apiKey)
        }
    }

    fun clearApiKey() {
        viewModelScope.launch {
            preferencesManager.clearApiKey()
        }
    }

    fun setAudioSource(source: AudioSource) {
        if (!_uiState.value.isRecording) {
            _uiState.value = _uiState.value.copy(selectedAudioSource = source)
        }
    }

    fun startTranslation(apiKey: String) {
        if (_uiState.value.isRecording) return
        
        viewModelScope.launch(Dispatchers.Main) {
            try {
                _uiState.value = _uiState.value.copy(
                    isRecording = true, 
                    error = null,
                    sourceTexts = emptyList(),
                    translations = emptyList()
                )

                // 先启动翻译服务
                val targetLanguages = when (_uiState.value.sourceLanguage) {
                    TranslationService.LANGUAGE_CHINESE -> listOf(
                        TranslationService.LANGUAGE_ENGLISH,
                        TranslationService.LANGUAGE_CANTONESE
                    )
                    TranslationService.LANGUAGE_ENGLISH -> listOf(
                        TranslationService.LANGUAGE_CHINESE,
                        TranslationService.LANGUAGE_CANTONESE
                    )
                    TranslationService.LANGUAGE_CANTONESE -> listOf(
                        TranslationService.LANGUAGE_CHINESE,
                        TranslationService.LANGUAGE_ENGLISH
                    )
                    else -> listOf(TranslationService.LANGUAGE_ENGLISH)
                }

                // 启动翻译服务并等待其就绪
                val translationJob = launch {
                    try {
                        translationService.startTranslation(
                            sourceLanguage = _uiState.value.sourceLanguage,
                            targetLanguages = targetLanguages,
                            apiKey = apiKey
                        ).collect { result ->
                            if (result.sourceText.isNotBlank()) {
                                _uiState.value = _uiState.value.copy(
                                    sourceTexts = _uiState.value.sourceTexts + result.sourceText,
                                    translations = _uiState.value.translations + result.translations
                                )
                                Timber.d("更新UI状态 - 源文本: ${result.sourceText}, 翻译: ${result.translations}")
                            }
                        }
                    } catch (e: Exception) {
                        Timber.e(e, "翻译服务异常")
                        _uiState.value = _uiState.value.copy(
                            error = "翻译服务异常: ${e.message}"
                        )
                        throw e
                    }
                }

                // 等待翻译服务启动完成
                kotlinx.coroutines.delay(500)

                // 启动音频录制
                withContext(Dispatchers.IO) {
                    currentAudioPath = audioRecorder.startRecording()
                }

                // 启动音频数据采集
                launch {
                    try {
                        audioRecordService.startRecording().collect { audioData ->
                            if (_uiState.value.isRecording && audioData.isNotEmpty()) {
                                translationService.sendAudioData(audioData)
                            }
                        }
                    } catch (e: Exception) {
                        Timber.e(e, "音频录制异常")
                        _uiState.value = _uiState.value.copy(
                            error = "音频录制异常: ${e.message}"
                        )
                        translationJob.cancel() // 取消翻译服务
                    }
                }
            } catch (e: Exception) {
                Timber.e(e, "启动翻译失败")
                _uiState.value = _uiState.value.copy(
                    isRecording = false,
                    error = "启动翻译失败: ${e.message}"
                )
                stopTranslation() // 确保清理资源
            }
        }
    }

    fun stopTranslation() {
        viewModelScope.launch {
            try {
                withContext(Dispatchers.IO) {
                    audioRecordService.stopRecording()
                    translationService.stopTranslation()
                    audioRecorder.stopRecording()
                    
                    // 保存记录
                    currentAudioPath?.let { audioPath ->
                        val record = TranslationRecord(
                            timestamp = Date(),
                            sourceLanguage = _uiState.value.sourceLanguage,
                            sourceText = _uiState.value.sourceTexts.joinToString(" "),
                            translations = _uiState.value.translations.lastOrNull() ?: emptyMap(),
                            audioFilePath = audioPath
                        )
                        translationDao.insert(record)
                    }
                }
                
                _uiState.value = _uiState.value.copy(isRecording = false)
                currentAudioPath = null
            } catch (e: Exception) {
                Timber.e(e, "停止翻译失败")
                _uiState.value = _uiState.value.copy(
                    error = "停止翻译失败: ${e.message}"
                )
            }
        }
    }

    fun setSourceLanguage(language: String) {
        if (!_uiState.value.isRecording) {
            _uiState.value = _uiState.value.copy(
                sourceLanguage = language,
                sourceTexts = emptyList(),
                translations = emptyList()
            )
        }
    }

    fun clearTranslations() {
        _uiState.value = _uiState.value.copy(
            sourceTexts = emptyList(),
            translations = emptyList()
        )
    }

    override fun onCleared() {
        super.onCleared()
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                audioRecordService.stopRecording()
                translationService.stopTranslation()
                if (_uiState.value.isRecording) {
                    audioRecorder.stopRecording()
                }
            }
        }
    }
} 
